package org.upt.dcda;

import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.upt.dcda.db.AuthorEntity;
import org.upt.dcda.exceptions.AuthorNotFoundException;
import org.upt.dcda.exceptions.BookstoreException;

/**
 * Session Bean implementation class AuthorManagerBean
 */
@Stateless
public class AuthorManagerBean implements AuthorManagerBeanRemote,
		AuthorManagerBeanLocal
{

	@PersistenceContext
	private EntityManager	entityManager;

	/**
	 * Default constructor.
	 */
	public AuthorManagerBean()
	{
		// TODO Auto-generated constructor stub
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public void addAuthor(String authorInfo, String authorName)
			throws BookstoreException
	{
		try
		{
			AuthorEntity author = new AuthorEntity(authorName, authorInfo);

			entityManager.persist(author);
		}
		catch (Throwable t)
		{
			throw new BookstoreException("Caught exception: " + t.toString(), t);
		}

	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public List<AuthorEntity> getAllAuthors() throws BookstoreException
	{
		try
		{

			Query query = entityManager
					.createNamedQuery(AuthorEntity.VIEW_ALL_AUTHORS);

			List<AuthorEntity> resultList = (List<AuthorEntity>) query
					.getResultList();
			return resultList;

		}
		catch (Throwable t)
		{
			throw new BookstoreException("Caught exception: " + t.toString(), t);
		}
	}

	@Override
	public AuthorEntity getAuthorById(int authorId) throws BookstoreException
	{
		try
		{
			AuthorEntity author = entityManager.find(AuthorEntity.class,
					authorId);
			if (author == null)
				throw new AuthorNotFoundException();
			return author;
		}
		catch (BookstoreException be)
		{
			throw be;
		}
		catch (Throwable t)
		{
			throw new BookstoreException("Caught exception: " + t.toString(), t);
		}
	}

}
